package data

import (
	"context"
	"demo/internal/conf"

	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/google/wire"
	_ "github.com/gogf/gf/contrib/drivers/mysql/v2"
)

type (
	contextTxKey struct{}
)

type Data struct {
	Orm gdb.DB
	cf  *conf.BaseConf
	bc  *conf.BootComponent
}

func NewData(cf *conf.BaseConf, bc *conf.BootComponent) *Data {
	return &Data{
		Orm: g.DB(),
		cf:  cf,
		bc:  bc,
	}
}

func (d *Data) InTx(ctx context.Context, fn func(ctx context.Context, tx gdb.TX) error) error {
	return d.Orm.Transaction(ctx, fn)
}

func (d *Data) Tx(ctx context.Context) (gdb.TX, context.Context, error) {
	tx, err := d.Orm.Begin(ctx)
	if err != nil {
		return nil, nil, err
	}
	ctx = context.WithValue(ctx, contextTxKey{}, tx)
	return tx, ctx, nil
}

// func (d *Data) DB(ctx context.Context) gdb.DB {
// 	tx, ok := ctx.Value(contextTxKey{}).(gdb.DB)
// 	if ok {
// 		return tx
// 	}
// 	return d.Mysql.WithContext(ctx)
// }

var Provider = wire.NewSet(NewData, NewUserRepo)
